package cn.hd01.export.impl;

import java.io.InputStream;
import java.text.SimpleDateFormat;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Row.MissingCellPolicy;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.NumberToTextConverter;
import org.springframework.stereotype.Component;

import cn.hd01.export.Importer;
import cn.hd01.export.RowProccess;
import cn.hd01.export.anno.Support;

@Component
@Support({ "xls", "xlsx" })
public class ExcelImporter implements Importer {

	public static final SimpleDateFormat DATA_FORMATER = new SimpleDateFormat("yyyyMMddHHmmss");

	@Override
	public <T> void importer(InputStream is, RowProccess<T> process) throws Exception {
		Workbook book = WorkbookFactory.create(is);
		book.setMissingCellPolicy(MissingCellPolicy.CREATE_NULL_AS_BLANK);

		Sheet sheet = book.getSheetAt(0);
		int fieldNum = sheet.getRow(0).getLastCellNum();
		for (int i = 1; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			String[] fields = new String[fieldNum];
			for (int j = 0; j < fieldNum; j++) {
				fields[j] = convertCellToString(row.getCell(j));
			}

			process.process(i, fields);
		}

	}

	@SuppressWarnings("deprecation")
	private static String convertCellToString(Cell cell) {
		switch (cell.getCellTypeEnum()) {
		case BOOLEAN:
			return Boolean.toString(cell.getBooleanCellValue());
		case STRING:
			return cell.getStringCellValue();
		case NUMERIC: {
			double value = cell.getNumericCellValue();
			if (DateUtil.isCellDateFormatted(cell)) {
				return DATA_FORMATER.format(DateUtil.getJavaDate(value));
			}
			return NumberToTextConverter.toText(value);
		}
		case FORMULA:
		case ERROR:
		case BLANK:
		default:
			return "";
		}
	}
}
